package com.example.demo.session.dao;


import java.io.Serializable;
import java.util.Collection;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;

import com.example.demo.service.SessionService;
import com.example.demo.service.impl.SessionServiceImpl;
import com.example.demo.util.SerializableUtils;

/**
 * 对{@link org.apache.shiro.session.Session}进行增删改查的类
 * <p>@author Henry.Y</p>
 * <p>@date 2019-08-30</p>
 */
public class MySessionDAO extends CachingSessionDAO{

	private SessionService sessionService= new SessionServiceImpl();
	
	protected Serializable doCreate(Session session){
		//printSomethings(session);
		Serializable sessionId= generateSessionId(session);
		assignSessionId(session,sessionId);
		sessionService.doCreate(session);
		System.out.println("调用插入session方法,插入id为".concat(String.valueOf(session.getId())));
		return session.getId();
	}
	
	protected void doDelete(Session session){
		//printSomethings(session);
		System.out.println("调用删除session的方法,id为".concat(String.valueOf(session.getId())));
		sessionService.deleteSession(session);
	}
	
	protected void doUpdate(Session session){
		//printSomethings(session);
		System.out.println("调用修改session的方法,id为".concat(String.valueOf(session.getId())));
		if(session instanceof ValidatingSession && ((ValidatingSession)session).isValid()){
			return ;
		}
		sessionService.updateSession(session);
	}
	
	protected Session doReadSession(Serializable sessionId){
		System.out.println("调用读取session的方法,id为".concat(String.valueOf(sessionId)));
		return SerializableUtils.deserialize(sessionService.doReadSession(sessionId).toString());
	}
	
	private void printSomethings(Session session){
		System.out.println("主机地址:"+session.getHost());
		System.out.println("最后登录时间:"+session.getLastAccessTime());
		System.out.println("过期时间:"+session.getTimeout());
		System.out.println("会话启动时间:"+session.getStartTimestamp());
		Collection<Session> collection=super.getActiveSessions();
		System.out.println(collection.size());
		/*System.out.println(session.getAttributeKeys().size());
		for(Object object:session.getAttributeKeys()){
			System.out.println(object.toString());
		}*/
	}
	
	
}
